<template>
  <div class="course-selection-container">
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索课程名称/代码/教师" 
            prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select 
            v-model="filterType" 
            placeholder="课程类型" 
            clearable
            @change="handleSearch"
          >
            <el-option label="必修课" value="必修课" />
            <el-option label="选修课" value="选修课" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-row :gutter="20" class="course-row">
      <el-col :span="16">
        <el-card class="course-card">
          <template #header>
            <div class="card-header">
              <h3>可选课程</h3>
              <div class="course-count">
                共 {{ filteredCourses.length }} 门课程
              </div>
            </div>
          </template>
          
          <el-empty v-if="filteredCourses.length === 0" description="没有找到匹配的课程" />
          
          <div v-else class="course-list">
            <el-table 
              :data="filteredCourses"
              style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa' }"
            >
              <el-table-column prop="code" label="课程代码" width="100" />
              <el-table-column prop="name" label="课程名称" width="180" />
              <el-table-column prop="teacher" label="教师" width="120" />
              <el-table-column prop="credits" label="学分" width="80" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.type === '必修课' ? 'danger' : 'success'">
                    {{ scope.row.type }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="容量" width="120">
                <template #default="scope">
                  <div>
                    {{ scope.row.enrolled }}/{{ scope.row.capacity }}
                    <el-progress 
                      :percentage="(scope.row.enrolled / scope.row.capacity) * 100"
                      :status="getCapacityStatus(scope.row)"
                      :stroke-width="5"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small"
                    :disabled="isSelected(scope.row.id) || isFull(scope.row)"
                    @click="selectCourse(scope.row)"
                  >
                    {{ isSelected(scope.row.id) ? '已选' : '选课' }}
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    @click="showCourseDetail(scope.row)"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="selected-card">
          <template #header>
            <div class="card-header">
              <h3>已选课程</h3>
              <div class="course-count">
                共 {{ courseStore.selectedCourses.length }} 门课程
              </div>
            </div>
          </template>
          
          <el-empty v-if="courseStore.selectedCourses.length === 0" description="暂无已选课程" />
          
          <div v-else class="selected-list">
            <div 
              v-for="course in courseStore.selectedCourses" 
              :key="course.id" 
              class="selected-item"
            >
              <div class="selected-info">
                <h4 class="selected-name">{{ course.name }}</h4>
                <div class="selected-details">
                  <span>{{ course.code }}</span>
                  <el-divider direction="vertical" />
                  <span>{{ course.teacher }}</span>
                  <el-divider direction="vertical" />
                  <span>{{ course.credits }}学分</span>
                </div>
                <div class="selected-schedule">
                  <div v-for="(s, index) in course.schedule" :key="index" class="schedule-item">
                    <el-tag size="small" class="schedule-tag">
                      {{ getDayText(s.day) }} {{ s.startTime }}-{{ s.endTime }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="selected-actions">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="dropCourse(course.id)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 课程详情对话框 -->
    <el-dialog
      v-model="courseDetailVisible"
      title="课程详情"
      width="500px"
    >
      <div v-if="selectedCourse" class="course-detail">
        <h3>{{ selectedCourse.name }} <el-tag>{{ selectedCourse.code }}</el-tag></h3>
        <div class="detail-item">
          <span class="detail-label">教师：</span>
          <span>{{ selectedCourse.teacher }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">学分：</span>
          <span>{{ selectedCourse.credits }} 学分</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">类型：</span>
          <span>{{ selectedCourse.type }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">容量：</span>
          <span>{{ selectedCourse.enrolled }}/{{ selectedCourse.capacity }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">上课时间：</span>
          <div>
            <div v-for="(s, index) in selectedCourse.schedule" :key="index">
              {{ getDayText(s.day) }} {{ s.startTime }} - {{ s.endTime }} ({{ s.location }})
            </div>
          </div>
        </div>
        <div class="detail-item">
          <span class="detail-label">课程描述：</span>
          <p>{{ selectedCourse.description }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button 
            v-if="!isSelected(selectedCourse?.id)"
            type="primary" 
            :disabled="isFull(selectedCourse)"
            @click="selectCourse(selectedCourse)"
          >
            选课
          </el-button>
          <el-button 
            v-else 
            type="danger" 
            @click="dropCourse(selectedCourse?.id)"
          >
            退选
          </el-button>
          <el-button @click="courseDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useCourseStore } from '../../stores/course'
import { ElMessage, ElMessageBox } from 'element-plus'

const courseStore = useCourseStore()

// 搜索和筛选
const searchKeyword = ref('')
const filterType = ref('')

// 课程详情
const courseDetailVisible = ref(false)
const selectedCourse = ref(null)

// 筛选后的课程列表
const filteredCourses = computed(() => {
  let courses = courseStore.courses
  
  // 按类型筛选
  if (filterType.value) {
    courses = courses.filter(course => course.type === filterType.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    courses = courses.filter(course => 
      course.name.toLowerCase().includes(keyword) || 
      course.code.toLowerCase().includes(keyword) || 
      course.teacher.toLowerCase().includes(keyword)
    )
  }
  
  return courses
})

// 判断课程是否已选
const isSelected = (courseId) => {
  return courseStore.selectedCourseIds.includes(courseId)
}

// 判断课程是否已满
const isFull = (course) => {
  if (!course) return false
  return course.enrolled >= course.capacity
}

// 获取容量状态
const getCapacityStatus = (course) => {
  const percent = (course.enrolled / course.capacity) * 100
  if (percent >= 100) return 'exception'
  if (percent >= 80) return 'warning'
  return 'success'
}

// 获取星期文本
const getDayText = (day) => {
  const days = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    7: '周日'
  }
  return days[day] || ''
}

// 显示课程详情
const showCourseDetail = (course) => {
  selectedCourse.value = course
  courseDetailVisible.value = true
}

// 选课
const selectCourse = (course) => {
  if (!course) return
  
  if (isSelected(course.id)) {
    ElMessage.warning('该课程已经选择')
    return
  }
  
  if (isFull(course)) {
    ElMessage.warning('该课程已满员')
    return
  }
  
  // 检查时间冲突
  const hasConflict = courseStore.selectedCourses.some(selectedCourse => {
    return course.schedule.some(newSchedule => {
      return selectedCourse.schedule.some(existingSchedule => {
        return newSchedule.day === existingSchedule.day && 
               newSchedule.startTime === existingSchedule.startTime
      })
    })
  })
  
  if (hasConflict) {
    ElMessageBox.confirm(
      '该课程与已选课程时间冲突，是否继续选课？',
      '时间冲突',
      {
        confirmButtonText: '继续选课',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      courseStore.selectCourse(course)
      ElMessage.success('选课成功')
      courseDetailVisible.value = false
    }).catch(() => {})
  } else {
    courseStore.selectCourse(course)
    ElMessage.success('选课成功')
    courseDetailVisible.value = false
  }
}

// 退选课程
const dropCourse = (courseId) => {
  if (!courseId) return
  
  ElMessageBox.confirm(
    '确定要退选该课程吗？',
    '退选确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    courseStore.dropCourse(courseId)
    ElMessage.success('退选成功')
    courseDetailVisible.value = false
  }).catch(() => {})
}

// 搜索处理
const handleSearch = () => {
  courseStore.setSearchKeyword(searchKeyword.value)
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  filterType.value = ''
  courseStore.setSearchKeyword('')
}
</script>

<style scoped>
.course-selection-container {
  padding: 0 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.course-row {
  margin-bottom: 20px;
}

.course-card,
.selected-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.course-count {
  font-size: 14px;
  color: #909399;
}

.course-list {
  margin-top: 10px;
}

.selected-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.selected-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.selected-info {
  flex: 1;
}

.selected-name {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.selected-details {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.selected-schedule {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.schedule-tag {
  margin-right: 5px;
}

.selected-actions {
  margin-left: 10px;
}

/* 课程详情 */
.course-detail {
  padding: 10px;
}

.course-detail h3 {
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
}

.detail-label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}
</style> 